<template>

  <div>
    <div style="width: 80%; margin-right: 10%; margin-left: 10%;">
      <el-select v-model="dataSource" placeholder="请选择" @change="initLogList">
        <el-option
          v-for="item in dataSourceList"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <div style="float: right">
        <el-input v-model="dataSourceInput" style="width: auto" placeholder="自定义数据源名称" />
        <el-button @click="submitDataSourceInput(dataSourceInput)">创建数据源</el-button>
      </div>
    </div>

    <el-card v-if="dataSource == null || dataSource === ''" style="width: 80%; margin-right: 10%; margin-left: 10%;">
      <el-empty description="暂无数据,可以通过下方或右上角的创建数据源或在左上角选择数据源开始记录你的导随(要导入数据得先创建一个空的数据源)">
        <div>
          <el-input v-model="dataSourceInput" style="width: auto" placeholder="自定义数据源名称" />
          <el-button @click="submitDataSourceInput(dataSourceInput)">创建数据源</el-button>
        </div>
      </el-empty>
    </el-card>


    <el-card v-if="dataSource != null && dataSource !== ''" style="width: 80%; margin-right: 10%; margin-left: 10%;">
      <div slot="header" class="clearfix">
        <span style="font-size: x-large"><i class="el-icon-s-management" />{{ dataSource }}</span>
        <span style="margin-left: 10px">-已导{{logList.index}}把</span>
        <el-button type="danger" plain style="float: right" @click="deleteDataSource">
          销毁当前数据源
        </el-button>

        <el-popover
            style="float: right"
            placement="bottom"
            width="400"
            trigger="click"
        >
          <div>
            最好转移到<a href="#" @click="downloadExampleExcel">示例模板(点击获取(根据你的设置动态生成))</a>上导入,可以保证导入数据的完整性
          </div>
          <br/>
          <div>
            当然尝试直接将原有表格导入也是可以的,可以在<router-link to="/settings">这里(点击跳转到右上角的<i class="el-icon-setting" />)</router-link>设置表头和自动替换后导入,列的顺序不影响导入,重点是设置表头和内容的对应关系
          </div>
          <br/>
          <div>
            职业和完成情况需要设置自动替换设置否则职业会识别为未知完成情况会默认完成
          </div>
          <div>
            <input id="excelFile" type="file" >
            <el-button @click="importExcel">导入excel</el-button>
          </div>
          <el-button slot="reference" type="success" plain>导入excel</el-button>
        </el-popover>
        <el-button style="float: right" @click="exportExcel" type="success" plain>导出为excel</el-button>

        <el-popover
            style="float: right"
            placement="bottom"
            width="400"
            trigger="click"
        >
          <div>从本站导出的json文件可以在这里导入</div>
          <div>
            <input id="jsonFile" type="file" accept=".json">
            <el-button @click="importJSON">导入json</el-button>
          </div>
          <el-button slot="reference">导入JSON</el-button>
        </el-popover>
        <el-button style="float: right" @click="exportJSON">导出为JSON</el-button>

<!--        <el-input style="float: right; width: 100px" v-model="logList.index"/>-->
        <el-tooltip class="item" effect="dark" content="完成场次异常时使用,这将影响完成总数的统计和表单中自动填写的完成场次" placement="left">
          <el-button style="float: right" @click="correctButton">校正场次</el-button>
        </el-tooltip>

        <el-button style="float: right" @click="sortButton">自动排序</el-button>

      </div>


      <el-button style="width: 100%" type="primary" @click="addButton">
        <i class="el-icon-plus" />
      </el-button>

      <div class="block">
        <el-pagination
            :current-page.sync="currentPage"
            layout="prev, pager, next"
            :page-size="pageCount"
            :total="logList.data.length">
        </el-pagination>
      </div>

      <el-table
        :data="logPageList"
        stripe
        :default-sort="{prop: 'count', order: 'descending'}"
      >

        <el-table-column
            prop="count"
            label="完成场次"
            sortable
            width="120"
        />

        <el-table-column
          prop="dungeon"
          label="副本"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="discipline"
          label="职业"
          width="100"
        >
          <template slot-scope="{ row }">
            <span style="margin-left: 10px">{{ disciplineNameMap.get(row.discipline) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="completed"
          label="完成情况"
          width="100"
        >
          <template slot-scope="{ row }">
            <span v-if="row.completed" style="margin-left: 10px">完成</span>
            <span v-if="!row.completed" style="margin-left: 10px">未完成</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述"
        >
          <template slot-scope="{ row }">
            <span style="margin-left: 10px">{{subDescription(row.description)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="date"
          label="日期"
          sortable
          width="200"
          :formatter="timeFormatter"
        />
        <el-table-column width="200">
          <template slot-scope="scope">
            <el-button @click="updateButton(scope)">详情</el-button>
            <el-popconfirm
                @confirm="deleteButton(scope)"
                title="确定删除该条记录吗"
            >
              <el-button slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>

      </el-table>
      <div class="block">
        <el-pagination
            :current-page.sync="currentPage"
            layout="prev, pager, next"
            :page-size="pageCount"
            :total="logList.data.length">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      title="添加导随记录"
      :visible.sync="dialog_add_visible"
      width="50%"
    >
      <el-form :label-position="labelPosition" label-width="80px" :model="log">
        <el-form-item label="完成场次">
          <el-input v-model="log.count"/>
        </el-form-item>
        <el-form-item label="副本名">
          <el-autocomplete
            v-model="log.dungeon"
            class="inline-input"
            :fetch-suggestions="querySearch"
            placeholder="支持空格隔开的多关键词搜索,如50 yifulite"
            :trigger-on-focus="false"
            style="width: 300px"
          >
          </el-autocomplete>

          <span v-if="log.dungeon != null && log.dungeon !==''" style="margin-left: 10px">
            <i v-if="checkDungeon(log.dungeon)" style="color: #42b983" class="el-icon-check"></i>
            <el-tooltip v-else class="item" effect="dark" content="当前是用户自定义的副本名,建议在下拉框中匹配正式副本名(以灰机wiki为准)使用" placement="right">
              <i class="el-icon-warning-outline" style="color: #fff100"></i>
            </el-tooltip>
          </span>


        </el-form-item>

        <el-form-item label="职业">
          <el-select v-model="log.discipline" placeholder="请选择职业">
            <el-option
              v-for="item of disciplineNameMap"
              :key="item[0]"
              :label="item[1]"
              :value="item[0]"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否完成">
          <el-switch v-model="log.completed" @change="onCompleteButtonChange" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="log.description" type="textarea" />
        </el-form-item>
        <el-form-item label="图片链接">
          <el-input v-model="log.image"></el-input>
          <img v-if="log.image !== '' && log.image != null" :src='log.image' alt='无法显示链接图片,请检查链接或联系开发人员'/>
          <a v-else href='https://postimages.org/' target='_blank'>打开建议的图床网站上传图片</a>
        </el-form-item>
        <el-form-item label="时间">
          <div class="block">
            <el-date-picker
              v-model="log.date"
              type="datetime"
              placeholder="选择日期时间"
              default-time="00:00:00"
              :picker-options="pickerOptions"
            />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button @click="dialog_add_visible = false">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <el-dialog
        title="修改导随记录"
        :visible.sync="dialog_update_visible"
        width="50%"
    >
      <el-form :label-position="labelPosition" label-width="80px" :model="updateLog">
        <el-form-item label="完成场次">
          <el-input v-model="updateLog.count"/>
        </el-form-item>
        <el-form-item label="副本名">
          <el-autocomplete
              v-model="updateLog.dungeon"
              class="inline-input"
              :fetch-suggestions="querySearch"
              placeholder="支持空格隔开的多关键词搜索,如50 yifulite"
              :trigger-on-focus="false"
              style="width: 300px"
          >
          </el-autocomplete>

          <span v-if="updateLog.dungeon != null && updateLog.dungeon !==''" style="margin-left: 10px">
            <i v-if="checkDungeon(updateLog.dungeon)" style="color: #42b983" class="el-icon-check"></i>
            <el-tooltip v-else class="item" effect="dark" content="用户自定义的副本名,建议在下拉框中匹配正式副本名使用" placement="right">
              <i class="el-icon-warning-outline" style="color: #fff100"></i>
            </el-tooltip>
          </span>


        </el-form-item>

        <el-form-item label="职业">
          <el-select v-model="updateLog.discipline" placeholder="请选择职业">
            <el-option
                v-for="item of disciplineNameMap"
                :key="item[0]"
                :label="item[1]"
                :value="item[0]"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否完成">
          <el-switch v-model="updateLog.completed" @change="onCompleteButtonChange" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="updateLog.description" type="textarea" />
        </el-form-item>
        <el-form-item label="图片链接">
          <el-input v-model="updateLog.image"></el-input>
          <img v-if="updateLog.image !== '' && updateLog.image != null" :src='updateLog.image' alt='无法显示链接图片,请检查链接或联系开发人员'/>
          <a v-else href='https://postimages.org/' target='_blank'>打开建议的图床网站上传图片</a>
        </el-form-item>
        <el-form-item label="时间">
          <div class="block">
            <el-date-picker
                v-model="updateLog.date"
                type="datetime"
                placeholder="选择日期时间"
                default-time="00:00:00"
                :picker-options="pickerOptions"
            />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onUpdate">修改</el-button>
          <el-button @click="dialog_add_visible = false">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

  </div>
</template>

<script>
import { getDefaultLog, getExcelKey } from '@/api/settings'
import { DisciplineConsts, DisciplineName, SampleData } from '@/consts/Consts'
import { checkDungeonName, getDungeons } from '@/api/service/dungeonsService'
import { parseTime,getPickerOptions } from '@/utils'
import FileSaver from 'file-saver'
import * as LogService from '@/api/service/logService'
import * as DataSourceService from '@/api/service/dataSourceService'
import * as XlsxUtils from '@/utils/xlsxUtils'
import { formatLogListToExcel, formatLogListFromExcel } from "@/utils/logFormatUtils";

export default {
  data() {
    return {
      labelPosition: 'left',
      dataSource: '',
      dataSourceInput: '',
      dataSourceList: DataSourceService.initDataSource(),
      dialog_add_visible: false, // 表单对话框开启和关闭
      dialog_update_visible: false, // 表单对话框开启和关闭
      index: -1, // 当前选中行的下标
      logList: {},
      currentPage: 1,
      pageCount: 100,
      disciplineConsts: DisciplineConsts,
      disciplineNameMap: new Map(DisciplineName),
      excelKey: getExcelKey(),
      log: {},
      updateLog: {},
      pickerOptions: getPickerOptions()
    }
  },
  computed:{
    logPageList: function (){
      // 正序
      // return this.logList.data.slice((this.currentPage - 1)*this.pageCount, (this.currentPage - 1)*this.pageCount + this.pageCount)
      let start = this.logList.data.length - ((this.currentPage - 1)*this.pageCount + this.pageCount)
      start = start > 0 ? start : 0
      return this.logList.data.slice(
          start
          ,this.logList.data.length - (this.currentPage - 1)*this.pageCount
      )
    },
  },
  created() {
    this.initLogList()
    this.initLog()
  },
  methods: {
    initLogList() {

      if (this.dataSource == null || this.dataSource === '') {
        this.dataSource = this.dataSourceList[0]
      }

      const log = LogService.init(this.dataSource)
      if (log != null) {
        this.logList = log
      }
    },

    initLog() {
      this.log = JSON.parse(JSON.stringify(getDefaultLog()))
      this.log.count = (parseInt(this.logList.index) || 0) + 1
    },

    addButton() {
      this.dialog_add_visible = true
    },

    updateButton(scope) {
      this.updateLog = JSON.parse(JSON.stringify(scope.row))
      this.index = this.logList.data.indexOf(scope.row)
      this.dialog_update_visible = true
    },

    deleteButton(scope) {
      LogService.deleteLog(scope.row)
      this.$message({
        type: 'info',
        message: '已删除'
      });
    },

    correctButton(){
      LogService.correctIndex()
    },

    sortButton(){
      LogService.sort()
    },

    onSubmit() {
      const log = JSON.parse(JSON.stringify(this.log))
      LogService.addLog(log)
      this.dialog_add_visible = false
      this.initLog()
      this.$message({
        message: '记录成功',
        type: 'success'
      });
    },
    onUpdate() {
      this.dialog_update_visible = false
      LogService.updateLog(this.index, this.updateLog)
      this.index = -1
    },
    onCompleteButtonChange(b){
      this.log.count = b ? parseInt(this.logList.index) + 1 : -1
    },

    querySearch(queryString, cb) {
      const results = queryString ? getDungeons(queryString) : []
      // 调用 callback 返回建议列表的数据
      cb(results)
    },

    timeFormatter(row) {
      return parseTime(new Date(row.date), '')
    },

    // 导出json
    exportJSON() {
      // 将json转换成字符串
      const data = JSON.stringify(LogService.getLogList(this.dataSource))
      const blob = new Blob([data], { type: '' })
      FileSaver.saveAs(blob, this.dataSource + '.json')
    },
    // 导入json
    importJSON() {
      const file = document.getElementById('jsonFile').files[0]
      const reader = new FileReader()
      reader.readAsText(file)
      reader.onload = function() {
        // this.result为读取到的json字符串，需转成json对象
        LogService.addLogList(JSON.parse(this.result).data)
      }
    },

    importExcel() {
      const file = document.getElementById('excelFile').files[0]
      XlsxUtils.importExcel(file).then(rs => {
        let logList = formatLogListFromExcel(rs)
        LogService.addLogList(logList)
      })
    },

    exportExcel(){
      let formattedLogList = formatLogListToExcel(this.logList.data)
      XlsxUtils.exportExcel('开导！.xlsx', formattedLogList)
    },

    downloadExampleExcel(){
      let formattedLogList = formatLogListToExcel(SampleData.data)
      XlsxUtils.exportExcel('开导！.xlsx', formattedLogList)
    },

    submitDataSourceInput(dsName) {
      this.dataSource = dsName
      DataSourceService.addDataSource(this.dataSource)
      this.initLogList()
    },

    deleteDataSource(){
      this.$confirm('确定要销毁本数据源吗？销毁后就连缓存都会清除，清慎重考虑！建议销毁前先导出为excel或json作为备份！', '销毁' + this.dataSource, {
        confirmButtonText: '我已备份，确定要销毁这个叫\'' + this.dataSource +'\'的数据源',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        DataSourceService.deleteDataSource(this.dataSource)
        LogService.deleteLogList(this.dataSource)
        this.dataSource = undefined
        this.initLogList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    checkDungeon(name){
      return checkDungeonName(name)
    },

    subDescription(str){
      if (str.length > 15){
        return str.substring(0, 30) + '...'
      }
      return str
    },

    getLogListByPage(){
      return  this.logList.data.slice((this.currentPage - 1)*this.pageCount, (this.currentPage - 1)*this.pageCount + this.pageCount)
      // console.log(this.logList.data.slice(1,5))
    },

  }

}
</script>

<style scoped>

</style>
